<template>
  <div>
    <div class="formGroup">
      <el-form ref="form" class="form" :model="query" label-position="right">
        <el-form-item style="width: 400px; margin-right: 4px;" label="订单下单时间：" class="merge-item">
          <el-date-picker
            v-model="query.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="所属机构" class="merge-item">
          <el-tree-select
            v-model="query.orgSNNo"
            :clearable="false"
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择组织机构',
              loading: $loadingPlugin.getTreeData
            }"
            :tree-params=" {
              'default-expand-all': true,
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item style="margin-left: 5px;" label="归属人" class="merge-item">
          <el-select v-model="query.userId" :loading="$loadingPlugin.getOwnersList" style="width: 100%;" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in ownersList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="merge-item">
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="btnInfo">
        <!-- <i> -->
        <img v-if="swich==='map'" src="@/assets/map_images/red_sprite.png">
        <span v-if="swich==='map'">待派单({{ orderOne }})</span>
        <img v-if="swich==='map'" src="@/assets/map_images/blue_sprite.png">
        <span v-if="swich==='map'">已选中({{ orderTwo }})</span>
        <img v-if="swich==='map'" src="@/assets/map_images/green_sprite.png">
        <span v-if="swich==='map'">已派单({{ orderThree }})</span>
        <el-button class="btn" type="primary" @click="cut">{{ swich==="form"?'切换为地图模式':'切换为表格模式' }}</el-button>
      </div>
    </div>
    <div class="table_Main">
      <lb-table
        v-show="swich==='form'"
        ref="lbTable"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        class="left"
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        @selection-change="handleSelectionChange"
        @fetch="fetchData"
      />
      <div v-show="swich==='map'" class="left">
        <!-- scroll-wheel-zoom：是否可以用鼠标滚轮控制地图缩放 -->
        <baidu-map
          ref="map"
          :key="updateMap"
          :map-click="false"
          style="height: 800px;"
          :enable-drawing-tool="true"
          scroll-wheel-zoom
          class="order_map"
          :center="'武汉'"
          :zoom="10"
          @ready="handler"
        >
          <!-- <bm-marker v-for="(l,i) in tableData.data" :key="i" :title="l.orderCode " :position="{lng: l.lon, lat: l.lat}" @click="infoWindowOpen(l)">
            <bm-info-window class="infoWindow" :show="show" @close="infoWindowClose" @open="infoWindowOpen">
              <div style="display: flex; justify-content: space-between;">
                <span>订单号:{{ l.orderCode }}</span>
                <span>客户编号:{{ l.csmCode }}</span>
              </div>
              <div style="display: flex; justify-content: space-between;">
                <span>联系人:{{ l.contact }}</span>
                <span>联系电话:{{ l.contactPhone }}</span>
              </div>
              <div>
                <span>地址:{{ l.csmAddress }}</span>
              </div>
              <div>
                <span>商品描述:{{ l.goodsDesc }}</span>
              </div>
              <div style="display: flex; justify-content: space-between;">
                <span>下单时间:{{ parseTime(l.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </div>
            </bm-info-window>
          </bm-marker> -->
        </baidu-map>
      </div>
      <lb-table
        ref=""
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        class="right"
        highlight-current-row
        element-loading-text="加载中"
        :column="orgidData.column"
        :data="orgidData.data"
        :total="orgidData.total"
        height="100%"
        style="overflow: auto;"
        custom-column
      />
    </div>
    <orderDetail ref="orderDetail" />
    <!-- <orderCodeDetail ref="orderCodeDetail" /> -->
  </div>
</template>

<script>
  // import tabledata from './select.json'
  // import userOrgidData from './userOrgid.json'
  // import { csmTypeMap } from '@/utils/map'
  import { parseTime, formatColumnMap } from '@/utils'
  import { mapGetters } from 'vuex'
  import { batchUserOrder, queryOwnersList, queryOrderManageList, batchOrderTransfer, queryCsmTypeMap } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  var greenIcon = require('../../../assets/map_images/green_sprite.png')
  var blueIcon = require('../../../assets/map_images/blue_sprite.png')
  var redIcon = require('../../../assets/map_images/red_sprite.png')

  String.format = function(B) {
    var A = Array.prototype.slice.call(arguments, 1)
    return B.replace(/\{(\d+)\}/g, function(C, D) {
      return A[D]
    })
  }
  export default {
    name: 'batchDispath',
    components: {
      orderDetail: require('./orderDetail.vue').default
      // orderCodeDetail: require('@/views/orderCenter/orderManage/components/OrderDetails.vue').default
    },
    data() {
      return {
        swich: 'form',
        treeData: [],
        show: false,
        center: { lng: 116.404, lat: 39.915 },
        orderOne: 0,
        orderTwo: 0,
        orderThree: 0,
        csmTypeMapList: [],
        orderPointMarkers: [],
        updateMap: 0,
        ownersList: [],
        polygonPath: {
          editing: false,
          paths: [] // 绘制完成后的经纬度，其实是在画的时候动态push的，因为在点击的时候触发了 paintPolygon 函数
        },
        zoom: 3,
        query: {
          userId: null,
          date: []
        },
        seletctIdList: [],
        tableData: {
          total: 0,

          column: [
            {
              type: 'selection'
            },
            {
              prop: 'orderCode',
              label: '单号',
              align: 'center',
              fixed: true
              // render: (h, { row }) => <el-link onClick={() => this.orderCodeDetail(row)}>{row.orderCode}</el-link>
            },
            {
              prop: 'csmAddress',
              label: '地址',
              align: 'left',
              width: 300,
              showOverflowTooltip: true

            },
            {
              prop: 'goodsCount',
              label: '商品数量',
              align: 'center'
            },
            {
              prop: 'ownerName',
              label: '归属人',
              align: 'center'

            },
            {
              prop: 'goodsDesc',
              align: 'center',
              label: '商品描述',
              showOverflowTooltip: true,
              width: 200
            },
            {
              prop: 'csmCode',
              align: 'center',
              label: '客户编号',
              width: 100,
              showOverflowTooltip: true
            },
            {
              prop: 'csmName',
              label: '客户名称',
              align: 'center',
              width: 100,
              showOverflowTooltip: true
            },
            {
              prop: 'contactPhone',
              label: '客户电话',
              align: 'center',
              width: 110

            },
            {
              prop: 'transactTime',
              label: '下单时间',
              align: 'left',
              width: 180,
              render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'appointmentDt',
              label: '配送时效区间',
              align: 'left',
              width: 180,
              render: (h, { row }) => <span>{ row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'remark',
              label: '备注',
              width: 250,
              showOverflowTooltip: true,
              align: 'left'
            },
            {
              prop: 'csmType',
              label: '客户类型',
              align: 'center',
              render: (h, { row }) => <span>{row.csmType ? formatColumnMap(this.csmTypeMapList, 'value', row.csmType, 'desc') : '' }</span>
            }
          ],
          data: []
        },
        orgidData: {
          column: [
            {
              prop: '',
              label: '',
              type: 'index',
              align: 'center'
              // render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.orderCode}</el-link>
            },
            {
              prop: '',
              label: '',
              align: 'center',
              width: 80,
              render: (h, { row }) => <el-link onClick={() => this.allot(row)}>分派至</el-link>
            },
            {
              prop: 'userName',
              label: '配送员名称',
              align: 'left',
              width: 120,
              showOverflowTooltip: true

            },
            {
              prop: 'orderCount',
              label: '订单数',
              align: 'center',
              width: 80,
              render: (h, { row }) => row.orderCount ? <el-link onClick={() => this.openOrderDetail(row)}>{row.orderCount}</el-link> : <span>{row.orderCount}</span>
            },
            {
              prop: 'goodsCount',
              label: '商品数',
              width: 80,
              align: 'center'

            }

          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await this.getTreeData()
      this.getCsmType()
    },
    mounted() {
      // console.log(this.organization)

    },
    methods: {
      parseTime,
      // 点击订单号
      async openOrderDetail(row) {
        await this.$refs.orderCodeDetail.open(row)
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        console.log({ ...this.query }, 'query')
        const params = {
          currentPage,
          pageSize,
          orderStatus: 2,
          orgSNNo: this.query.orgSNNo,
          ownerId: this.query.userId
        }
        if (this.query.date && this.query.date.length) {
          params['transactTime'] = this.query.date[0]
          params['transactTimeEnd'] = this.query.date[1]
        }
        for (var value in params) {
          if (!params[value]) {
            delete params[value]
          }
        }
        const res = await queryOrderManageList(params)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        await this.getUserOrder()
        await this.updateMap++
      },
      async getUserOrder() {
        const params = {
          orgSNNo: this.query.orgSNNo || ''
        }
        const res = await batchUserOrder(params)
        // orgidData
        this.orgidData.data = res.data
      },
      addZoom() {
        // console.log(this.$refs.map)
      },
      infoWindowClose() {
        this.show = false
      },
      infoWindowOpen() {
        this.show = true
      },
      // 机构数据
      async getTreeData() {
        // const res = await organizationQueryList({})
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.userId = ''
        this.getOwnersList(value)
        await this.getUserOrder()
      },
      // 查询处理人列表
      async getOwnersList(org) {
        // const b = corpsetting.sp1 >> 2 & 0x01
        const res = await queryOwnersList({
          orgId: org ? org.orgId : -1
          // corpparm1: b
        })
        this.ownersList = res.data
      },
      // 地图点的点击事件
      clickMarker(l) {
        console.log(event.srcElement.style)
      },
      // 查询
      search() {
        this.fetchData({})
      },
      async getCsmType() {
        const res = await queryCsmTypeMap()
        this.csmTypeMapList = res.data
      },
      // 点击选择
      handleSelectionChange(val) {
        console.log(val)
        this.seletctIdList = val.map(l => {
          return { orderCode: l.orderCode, ownerId: l.ownerId, ownerName: l.ownerName }
        })
      },
      // 分派
      allot(row) {
        if (this.swich === 'map') {
          console.log(this.orderPointMarkers, 'vm.orderPointMarkers')
          console.log(row, 'this.row')
          var markerPoints = this.orderPointMarkers
          var list = []
          if (markerPoints.length > 0) {
            for (var x = 0; x < markerPoints.length; x++) {
              var imageUrl = markerPoints[x].getIcon().imageUrl
              if (imageUrl === blueIcon) {
                list.push(markerPoints[x])
              }
            }
          }
          console.log(list, 'list')
          const num = list.length
          if (!num) {
            this.$message.warning('请先选择订单')
            return false
          }
          this.$confirm(`是否将选中的${num}个订单分配给${row.userName}`).then(async() => {
            const orderBillInfoList = list.map(l => {
              return { ...row, ...l.submitParam }
            })
            const params = {
              json: { orderBillInfoList }
            }
            const res = await batchOrderTransfer(params)
            if (res.success) {
              this.$message.success('分派成功')
              this.fetchData({})
            }
            console.log(orderBillInfoList)
          }).catch(e => {
            console.log(e)
          })
          return '地图模式分派'
        }
        // 表格模式分派
        const num = this.seletctIdList.length
        if (!num) {
          this.$message.warning('请先选择订单')
          return false
        }
        this.$confirm(`是否将选中的${num}个订单分配给${row.userName}`).then(async() => {
          const orderBillInfoList = this.seletctIdList.map(l => {
            return { ...row, ...l }
          })
          const params = {
            json: { orderBillInfoList }
          }
          const res = await batchOrderTransfer(params)
          if (res.success) {
            this.$message.success('分派成功')
            this.fetchData({})
          }
          console.log(orderBillInfoList)
        }).catch(e => {
          console.log(e)
        })
      },
      // 切换模式
      cut() {
        if (this.swich === 'form') {
          this.seletctIdList = []
          this.$refs.lbTable.clearSelection()
          this.swich = 'map'
        } else {
          this.swich = 'form'
          this.seletctIdList = []
        }
      },
      handler({ BMap, map }) {
        const vm = this
        var poi = new BMap.Point(116.307852, 40.057031)
        map.centerAndZoom(poi, 16)
        var overlays = []
        vm.orderPointMarkers = [] // 初始化点
        // 更新数量
        vm.orderNumCount()
        //
        var data = vm.tableData.data
        console.log(data, 'data')
        if (data.length > 0) {
          for (var x = 0; x < data.length; x++) {
            if (!(data[x].lon * 1) || !(data[x].lat * 1)) {
              continue
            }
            // 设置覆盖物图标
            var icon = new BMap.Icon(redIcon, new BMap.Size(19, 25))
            // var greenicon = require('@assets/map_images/green_sprite')
            if (data[x].intSpare6 >> 8 & 0x01 === 1) {
              icon.imageUrl = greenIcon
            }
            // 是否选中
            icon.bean = data[x]
            icon.bean.isChecked = false
            var pt = new BMap.Point(data[x].lon, data[x].lat)
            var marker = new BMap.Marker(pt, { icon: icon })
            // 表示障碍物 没有点击
            // icon.imageUrl = "/image/map/marker_red_sprite.png";
            var template = "<span style='margin-right: 20px;height: 28px;display:inline-block;width: 200px;'>订&ensp;单&ensp;号： {0}</span><span style='height: 28px;display:inline-block;'> 客户编号： {1}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;width: 200px;'>联&ensp;系&ensp;人： {2}</span><span style='height: 28px;display:inline-block;'>联系电话： {3}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>地&ensp;&ensp;&ensp;&ensp;址： {4}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>商品描述： {5}</span><br/>"
            template = template + "<span style='margin-right: 20px;height: 28px;display:inline-block;'>下单时间： {6}</span><br/>"
            marker.orderCode = data[x].orderCode || ''
            marker.csmCode = data[x].csmCode || ''
            marker.contact = data[x].contact || ''
            marker.contactPhone = data[x].contactPhone || ''
            marker.csmAddress = data[x].csmAddress || ''
            marker.goodsDesc = data[x].goodsDesc || ''
            marker.transactTime = vm.parseTime(data[x].transactTime, '{y}-{m}-{d} {h}:{i}:{s}') || ''
            marker.submitParam = { orderCode: data[x].orderCode, ownerId: data[x].ownerId, ownerName: data[x].ownerName }

            marker.addEventListener('mouseover', function() {
              var content = String.format(template, this.orderCode, this.csmCode, this.contact, this.contactPhone, this.csmAddress, this.goodsDesc, this.transactTime)
              var tempInfoWindow = new BMap.InfoWindow(content, {
                width: 400, // 信息窗口宽度
                height: 200, // 信息窗口高度
                title: '', // 信息窗口标题
                enableMessage: true// 设置允许信息窗发送短息
              })
              this.openInfoWindow(tempInfoWindow)
            })
            marker.addEventListener('mouseout', function() {
              this.closeInfoWindow()
            })

            marker.addEventListener('click', function(e) {
              var icon = this.getIcon()
              if (icon.bean.isChecked) {
                if (icon.bean.intSpare6 >> 8 & 0x01 === 1) {
                  icon.imageUrl = greenIcon
                } else {
                  icon.imageUrl = redIcon
                }
                icon.bean.isChecked = false
                this.setIcon(icon)
              } else {
                icon.imageUrl = blueIcon
                // 是否选中
                icon.bean.isChecked = true
                this.setIcon(icon)
              }
              // 更新数量
              vm.orderNumCount()
            })
            vm.orderNumCount()
            // marker.setAnimation(BMAP_ANIMATION_BOUNCE) // 跳动的动画
            // 增加点
            map.addOverlay(marker) // 将标注添加到地图中
            // 存储所有marker
            vm.orderPointMarkers.push(marker)
          }
          // console.log(vm.orderPointMarkers)
        }
        //

        var overlaycomplete = function(e) {
          overlays.push(e.overlay)
          switch (e.drawingMode) {
          // 图像标注
          case 'marker':break
          // 线的样式
          case 'polyline':

            break
          // 圆
          case 'circle':
            break
          // 多边形
          case 'polygon':
            break
          // 矩形
          case 'rectangle':
            var data = vm.tableData.data
            if (data.length > 0) {
              for (var x = 0; x < data.length; x++) {
                if (data[x].lon === undefined || data[x].lat === undefined) {
                  continue
                }
                var pt = new BMap.Point(data[x].lon, data[x].lat)
                // 矩形  或  多边形
                if (window.BMapLib.GeoUtils.isPointInPolygon(pt, e.overlay)) {
                  var markers = vm.orderPointMarkers
                  if (markers.length > 0) {
                    for (var a = 0; a < markers.length; a++) {
                      var markerIcon = markers[a].getIcon()
                      if (markerIcon.bean !== undefined) {
                        if (markerIcon.bean.orderCode === data[x].orderCode) {
                          markerIcon.imageUrl = blueIcon
                          // 是否选中
                          markerIcon.bean.isChecked = true
                          markers[a].setIcon(markerIcon)
                        }
                      }
                    }
                  }
                }
              }
            }
            break
          }
          // 地图上移除覆盖物
          clearAll()
          // 更新数量
          vm.orderNumCount()
          // console.log(overlays[0].Wu.getNorthEast())
        }
        var styleOptions = {
          strokeColor: 'red', // 边线颜色。
          fillColor: 'red', // 填充颜色。当参数为空时，圆形将没有填充效果。
          strokeWeight: 3, // 边线的宽度，以像素为单位。
          strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
          fillOpacity: 0.6, // 填充的透明度，取值范围0 - 1。
          strokeStyle: 'solid' // 边线的样式，solid或dashed。
        }
        // 实例化鼠标绘制工具
        var drawingManager = new window.BMapLib.DrawingManager(map, {
          isOpen: false, // 是否开启绘制模式
          enableDrawingTool: true, // 是否显示工具栏
          drawingToolOptions: {
            anchor: window.BMAP_ANCHOR_TOP_RIGHT, // 位置
            offset: new BMap.Size(5, 5) // 偏离值
          },
          circleOptions: styleOptions, // 圆的样式
          polylineOptions: styleOptions, // 线的样式
          polygonOptions: styleOptions, // 多边形的样式
          rectangleOptions: styleOptions // 矩形的样式
        })
        document.querySelectorAll('.order_map .BMapLib_marker')[0].style.display = 'none'
        document.querySelectorAll('.order_map .BMapLib_circle')[0].style.display = 'none'
        document.querySelectorAll('.order_map .BMapLib_polyline')[0].style.display = 'none'
        document.querySelectorAll('.order_map .BMapLib_polygon')[0].style.display = 'none'
        // 添加鼠标绘制工具监听事件，用于获取绘制结果
        drawingManager.addEventListener('overlaycomplete', overlaycomplete)
        function clearAll() {
          for (var i = 0; i < overlays.length; i++) {
            map.removeOverlay(overlays[i])
          }
          overlays.length = 0
        }
        // map.enableScrollWheelZoom(true)
        // map.centerAndZoom('青岛市', 13)
      },
      orderNumCount() {
        const vm = this
        var orderOne = 0
        var orderTwo = 0
        var orderThree = 0
        var markerPoints = vm.orderPointMarkers
        if (markerPoints.length > 0) {
          for (var x = 0; x < markerPoints.length; x++) {
            var imageUrl = markerPoints[x].getIcon().imageUrl
            // 红色
            if (imageUrl === redIcon) {
              orderOne = orderOne + 1
              // 蓝色
            } else if (imageUrl === blueIcon) {
              orderTwo = orderTwo + 1
              // 绿色
            } else if (imageUrl === greenIcon) {
              orderThree = orderThree + 1
            }
          }
        }
        this.orderOne = orderOne
        this.orderTwo = orderTwo
        this.orderThree = orderThree
        // console.log(orderOne, orderTwo, orderThree)
      }
      // 订单数详情
      // openOrderDetail(row) {
      //   this.$refs.orderDetail.open(row)
      // }

    }

  }

</script>

<style lang='scss' scoped>
.form {
  display: flex;
}
.formGroup {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.table_Main {
  display: flex;
  .left {
    width: 70%;
  }
}
.bm-view {
  width: '100%';
  height: '500px';
}
.infoWindow {
  width: 350px;
  height: 150px;
  padding: 5px;
  font-size: 14px;
  div {
    margin-top: 10px;
  }
}
.btnInfo {
  display: flex;
  font-size: 14px;
  // height:20px;
  img {
    width: 15px;
    height: 20px;
  }
  span {
    margin-right: 8px;
    line-height: 20px;
    text-align: center;
  }
  .btn {
    flex: 1;
  }
}

</style>
